/***********
  @name: 融媒体投递组件
  @describtion:
    1、选择投递平台
    2、投递确认及状态展示
    3、编辑投递配置（栏目选择，公众号配置等）
  props:
    * update:showDialog: 控制显示与关闭弹窗
    * pushData
      * pushList: 文章id列表
      * catid: catid
      * isAllChoose: 是否全选
***********/
<template>
  <div class="ruifox-media-push" :class="{'ruifox-media-push-step': pushConfig.pushStep === 1 || pushConfig.pushStep === 2}">
    <el-dialog
        v-model="showDialog"
        title="投递至"
        :width="dialogWidth"
        @close="handleClose"
        class="media-push-dialog"
        align-center
    >
      <div class="push-step push-type-choose" v-if="pushConfig.pushStep === 1">
        <div class="push-type-box">
          <h2>内部媒体投递:</h2>
          <div class="inner-push-type-box">
            <!-- 内部媒体投递id: 1 -->
            <div class="push-type-item" v-for="item in insideType" :key="item.id" @click="handleCheckInside(item.id)" :class="{'checked': pushConfig.pushInsideType.includes(item.id)}">
              <div class="check-box">
                <div class="check-box-bg">
                  <el-icon><Check /></el-icon>
                </div>
              </div>
              <div class="inner-push-type-item">
                <p class="type-title"><i class="iconfont" v-html="item.icon"></i>{{item.name}}</p>
                <span class="type-desc">{{item.description}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="push-type-box">
          <h2>外部媒体投递:</h2>
          <div class="inner-push-type-box" v-loading="pushTypeListLoading">
            <div class="push-type-item" v-for="item in mediaList" :key="item.id" :class="{'is-disabled': item.enable === 0,'checked': pushConfig.pushWithoutType.includes(item.id)}" @click="handleCheckWithout(item)">
              <div class="check-box" v-if="item.enable !== 0">
                <div class="check-box-bg">
                  <el-icon><Check /></el-icon>
                </div>
              </div>
              <div class="inner-push-type-item">
                <p class="type-title">
                  <Icon :name="item.icon" :type="'iconfontMedia'" :style="{color: item.icon_color}"/>
                  {{item.name}}
                </p>
                <span class="type-desc">{{item.description}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="push-type-confirm" v-if="pushConfig.pushStep === 2">
        <h2>内容将投递并发布至以下<span>{{confirmType.length}}</span>个媒体：</h2>
        <div class="confirm-type-box">
          <div class="confirm-type-item inside-type" v-for="item in confirmInsideType" :key="item.id">
            <div class="inner-confirm-type category-push" v-if="item.id === 1">
              <h3>
                <i class="iconfont" v-html="item.icon"></i>
                {{item.name}}
              </h3>
              <div class="push-message" >
                <div v-if="categoryChooseConfirm.length === 0" class="no-category">
                  <p><i class="iconfont">&#xe687;</i>您尚未选择栏目！</p>
                </div>
                <div v-else class="has-category">
                  <i class="iconfont">&#xe655;</i>
                  <div class="category-list">
                    <li v-for="item in categoryChooseConfirm.slice(0,3)" :key="item.id">
                      {{item.path}}
                    </li>
                    <el-collapse-transition>
                      <div class="more-list" v-show="showCategoryMore">
                        <li v-for="item in categoryChooseConfirm.slice(3-categoryChooseConfirm.length)" :key="item.id">
                          {{item.path}}
                        </li>
                      </div>
                    </el-collapse-transition>
                    <div v-if="categoryChooseConfirm.length > 0">
                      <span>等{{categoryChooseConfirm.length}}个栏目</span>
                      <el-button type="primary" text @click="handleToggleMoreCategory">{{ showCategoryMore ? '收起' : '展开' }}</el-button>
                    </div>
                  </div>
                </div>
              </div>
              <div class="push-option">
                <a href="javascript:;" class="push-option-btn" @click="handleGoChooseCategory">选择栏目</a>
              </div>
            </div>
          </div>
          <div class="confirm-type-item without-type" v-for="item in confirmWithoutType" :key="item.id">
            <div class="inner-confirm-type">
              <h3>
                <Icon :name="item.icon" :type="'iconfontMedia'" :style="{color: item.icon_color}"/>
                {{item.name}}
              </h3>
              <div class="push-message">
                <p class="is-loading" v-if="item.isGenerating">
                  <el-icon class="is-loading">
                    <Loading />
                  </el-icon>
                  正在生成媒体内容...
                </p>
                <div class="loaded" v-else>
                  <i
                     class="iconfont success"
                     v-html="item.needComplete.length === 0 ? item.failData.length === 0 ? '&#xe655;' : '&#xe60e;' : '&#xe687;'"
                     :class="{'error': item.needComplete.length > 0,'warning': item.failData.length > 0}">
                  </i>
                  <p>
                    <span v-if="item.pushData.length > 0">已生成<strong>{{item.pushData.length}}</strong>条内容</span>
                    <span v-if="item.needComplete.length > 0" class="error">其中有<strong>{{item.needComplete.length}}</strong>条内容需要完善，请点击"编辑"进行处理</span>
                    <span v-if="item.failData.length > 0" class="error">有<strong>{{item.failData.length}}</strong>条内容不可投递</span>。
                  </p>
                </div>
              </div>
              <div class="push-option">
                <a href="javascript:;" class="push-option-btn" @click="handleEditWithoutMedia(item)">编辑</a>
                <a href="javascript:;" class="push-option-btn" @click="handleViewDetail(item)">查看详情</a>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="push-category-choose" v-if="pushConfig.pushStep === 1000">
        <div class="push-category-btn">
          <el-button type="primary" @click="handleChooseCategory">选择栏目</el-button>
           <el-button @click="handleChooseCommonCategory">常用栏目</el-button>
        </div>
        <div class="category-choose-box">
          <div class="category-choose-list" v-show="categoryChoose.length > 0">
            <el-scrollbar height="430px">
              <div class="category-choose-item" v-for="(item,index) in categoryChoose" :key="item.id">
                <div class="choose-item-left">
                  <span class="choose-item-id">{{index+1}}</span>
                  <p class="choose-item-title">
                    {{item.path}}
                  </p>
                </div>
                <div class="choose-item-right">
                  <a href="javascript:;" class="push-option-btn" @click="handleRemoveCategory(index)">删除</a>
                </div>
              </div>
            </el-scrollbar>
          </div>
          <div class="no-data" v-show="categoryChoose.length === 0">
            <i class="iconfont">&#xe642;</i>
            <p>暂无栏目信息，点击下方选择栏目</p>
            <el-button type="primary" @click="handleChooseCategory">选择栏目</el-button>
          </div>
           <!-- 栏目选择弹框 -->
            <DialogTree
                v-model:showDialog="showChooseDialog"
                :pushCategoryList="pushCategoryList"
                @treeChoosed="treeChoosed"
            ></DialogTree>
          <el-dialog
              title="常用栏目"
              v-model="showChooseCommonDialog"
              width="640px"
              align-center
          >
            <div class="category-tree-box">
              <div class="common-list">
                <div class="common-item" v-for="item in pushCategoryCommonList" :key="item.id" @click="handleCommonChoose(item)">
                  <el-checkbox v-model="item.checked" @click.prevent="handleTreeCheck" style="margin-right: 10px;"></el-checkbox>
                  <span>{{item.path}}</span>
                </div>
              </div>
            </div>
            <template #footer>
            <span class="dialog-footer">
            <el-button type="primary" @click="handleTreeChoosed">确认</el-button>
            <el-button @click="handleCancelChooseCategoryUser">取消</el-button>
            </span>
            </template>
          </el-dialog>
        </div>
      </div>
      <!-- 查看详情 -->
      <div class="push-without-detail" v-if="pushConfig.pushStep === 3">
        <div class="detail-title">
          <h3>内容列表</h3>
          <div>单次可发布数量:<p><span>{{currentArticleCheckList.length}}</span>/{{currentMedia.publish_limit}}</p></div>
        </div>
        <div class="inner-detail">
          <el-scrollbar>
            <li v-for="item in currentArticleList" :key="item.id">
              <div class="inner-detail-left">
                <el-checkbox style="margin-right: 20px;" v-model="item.checked" :disabled="item.can_push === 0" @change="handleCheckedArticleList(item)"></el-checkbox>
                <span class="model-tip">{{item.islink !== '' ? '链接' : props.pushData.modelName}}</span>
                <p :class="{'is-disabled': item.can_push === 0}">{{item.title}}</p>
              </div>
              <div class="inner-detail-right">
                <el-tooltip
                    v-if="item.can_push === 0"
                    :content="item.islink !== '' ? item.status === 99 ? '该文章状态为“待发布”,不可投递' : '该文章状态为“审核中”,不可投递' : '链接不可投递至公众号'"
                    placement="bottom"
                    effect="light"
                >
                  <el-tag :type="item.status === 99 ? 'success' : 'warning'">{{item.status === 99 ? '已发布' : '审核中'}}</el-tag>
                </el-tooltip>
                <el-tag v-else type="success">已发布</el-tag>
              </div>
            </li>
          </el-scrollbar>
        </div>
      </div>
      <!-- 外部媒体编辑  组件插入 -->
      <div class="push-without-edit" v-if="pushConfig.pushStep === 4">
        <!-- 使用投递组件 -->
        <WechatPublishEdit v-if="currentMedia.component === 'WechatPublishEdit'" :articlesAdd="currentMedia.pushData" ref="publishDataRef"/>
      </div>
      <template #footer>
          <!-- 选择投递类型 -->
          <span class="dialog-footer" v-if="pushConfig.pushStep === 1">
              <el-button type="primary" @click="handleGoConfirm" :disabled="pushConfig.pushInsideType.length === 0 && pushConfig.pushWithoutType.length === 0" :loading="mediaGenerateLoading">
              下一步
              </el-button>
              <el-button @click="showDialog = false">取消</el-button>
          </span>
          <!-- 投递确认 -->
          <div class="dialog-footer-flex" v-if="pushConfig.pushStep === 2">
            <div class="footer-left">
            </div>
            <div class="footer-right">
              <el-button type="primary" @click="handleBatchPush" :loading="pushLoading">投递并发布</el-button>
              <el-button @click="handleBackTypeChoose">上一步</el-button>
            </div>
          </div>
          <!-- 栏目选择 pushStep: 1000 -->
          <div class="dialog-footer-flex" v-if="pushConfig.pushStep === 1000">
            <div class="footer-left">
              <el-button v-if="!soloPush" @click="handleBackTypeConfirm">返回上一级</el-button>
            </div>
            <div class="footer-right">
              <el-button type="primary" v-if="soloPush" @click="handlePushCategory" :disabled="categoryChoose.length === 0" :loading="pushLoading">投递</el-button>
              <el-button type="primary" v-else @click="handleSaveCategoryChoose" :disabled="categoryChoose.length === 0">保存</el-button>
              <el-button v-if="soloPush" @click="handleCancelPush">取消此次栏目投递</el-button>
              <el-button v-else @click="handleCancelCategoryPush">取消此次栏目投递</el-button>
            </div>
          </div>
          <!-- 外部媒体详情 -->
          <div class="dialog-footer-flex" v-if="pushConfig.pushStep === 3">
            <div class="footer-left">
              <el-button v-if="!soloPush" @click="handleBackTypeConfirm">返回上一级</el-button>
            </div>
            <div class="footer-right">
              <el-button type="primary" @click="handleGoMediaEdit" :loading="mediaGenerateLoading">下一步</el-button>
              <el-button v-if="soloPush" @click="handleCancelPush">取消本次{{currentMedia.name}}投递</el-button>
              <el-button v-else @click="handleCancelWithoutMediaPush">取消本次{{currentMedia.name}}投递</el-button>
            </div>
          </div>
          <div class="dialog-footer-flex" v-if="pushConfig.pushStep === 4">
            <div class="footer-left"></div>
            <div class="footer-right">
              <el-button type="primary" v-if="soloPush" @click="handlePushWithout">投递</el-button>
              <el-button type="primary" v-else @click="handleSaveWithoutEdit">保存编辑</el-button>
              <el-button v-if="directEdit" @click="handleBackTypeConfirm">上一步</el-button>
              <el-button v-else @click="handleBackArticleList">上一步</el-button>
            </div>
          </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, watch, computed } from 'vue'
import { Check, Loading } from '@element-plus/icons-vue'
import {getArticleList, getPushMediaList, mediaContentGenerate, pushMediaArticle} from "@/api/media";
import { canPushCategoryList } from "@/api/category";
import { createTreeData } from '@ruifox-cms/utils'
import { ElMessage } from 'element-plus'
import {getCommonCategory, pushContent} from '@/api/content'
import WechatPublishEdit from "@/components/stationContentChildren/WechatPublishEdit";
import { useStore } from 'vuex'
const store = useStore()

const dialogWidth = ref('960px')
const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  pushData: {
    type: Object
  }
})
const insideType = reactive([
  {
    id: 1,
    name: '网站栏目',
    icon: '&#xe66c;',
    description: '将内容同步投递到其他栏目',
  }
])
const defaultPushConfig = {
  pushStep: 1,
  pushInsideType: [],
  pushWithoutType: []
}
const pushConfig = reactive(Object.assign({},defaultPushConfig))
const emit = defineEmits(['update:showDialog'])
const showDialog = ref(props.showDialog)
const pushLoading = ref(false)  // 投递加载状态

watch(() => props.showDialog,(newVal) => {
  showDialog.value = newVal
},{deep:true})
const pushTypeListLoading = ref(false)
const mediaList = ref([])
watch(()=> props.pushData, newVal => {
  // 通过catid获取可以投递的外部媒体列表
  Object.assign(pushConfig,defaultPushConfig)
  pushConfig.pushInsideType = []
  pushConfig.pushWithoutType = []
  mediaList.value = []
  pushTypeListLoading.value = true
  getPushMediaList({catid: newVal.catid}).then((res) => {
    mediaList.value = res.data
    pushTypeListLoading.value = false
  })
},{deep: true})

// 选择投递媒体
const handleCheckInside = (id) => {
  if(pushConfig.pushInsideType.indexOf(id) !== -1){
    pushConfig.pushInsideType.splice(pushConfig.pushInsideType.indexOf(id),1)
  }else{
    pushConfig.pushInsideType.push(id)
  }
}
const handleCheckWithout = (data) => {
  if(data.enable === 0) return
  if(pushConfig.pushWithoutType.indexOf(data.id) !== -1){
    pushConfig.pushWithoutType.splice(pushConfig.pushWithoutType.indexOf(data.id),1)
  }else{
    pushConfig.pushWithoutType.push(data.id)
  }
}

// 投递确认数组
const showCategoryMore = ref(false)
const soloPush = ref(false)   // 是否单独投递
const confirmInsideType = ref([])
const confirmWithoutType = ref([])
const confirmType = computed(() => {
  return confirmInsideType.value.concat(confirmWithoutType.value)
})
const handleGoConfirm = () => {
  // 1.栏目选择清空
  categoryChoose.value = []
  categoryChooseConfirm.value = []
  // 判断是否单独内部投递
  if(pushConfig.pushInsideType.length === 1 && pushConfig.pushWithoutType.length === 0 && pushConfig.pushInsideType[0] === 1){
    pushConfig.pushStep = 1000
    soloPush.value = true
  }else{
    confirmInsideType.value = pushConfig.pushInsideType.map(id => {
      let _item = insideType.find(item => item.id === id)
      _item.checked = true
      return _item
    })
    confirmWithoutType.value = pushConfig.pushWithoutType.map(id => {
      let _item = mediaList.value.find(item => item.id === id)
      _item.checked = true
      // 是否在生成
      _item.isGenerating = true
      return _item
    })
    // 是否外部单独投递
    if(pushConfig.pushInsideType.length === 0 && pushConfig.pushWithoutType.length === 1){
      soloPush.value = true
      mediaGenerateAwait(confirmWithoutType.value[0])
    }else{
      soloPush.value = false
      // 调用媒体生成接口
      mediaGenerate(confirmWithoutType.value)
      pushConfig.pushStep = 2
    }
  }
}
// 展开收起
const handleToggleMoreCategory = () => {
  showCategoryMore.value = !showCategoryMore.value
}
// 返回type选择
const handleBackTypeChoose = () => {
  pushConfig.pushStep = 1
  // 内部媒体选择清空
  categoryChooseConfirm.value = []
}
const handleBackTypeConfirm = () => {
  pushConfig.pushStep = 2
  categoryChoose.value = []
}
const handleCancelCategoryPush = () => {
  pushConfig.pushStep = 2
  categoryChoose.value = []
  confirmInsideType.value.find(item => item.id === 1).checked = false
}

const resetDialogWidth = () => {
  dialogWidth.value = '960px';
}
const handleClose = () => {
  emit('update:showDialog',false)
  resetDialogWidth()
}
/**************************************************栏目流程******************************************************/

const categoryChooseConfirm = ref([])
const categoryChoose = ref([])
const categoryChooseWait = ref([])
const categoryChooseIds = computed(() => {
  return categoryChooseWait.value.map(item => {return item.id})
})
const pushCategoryList = ref([])
const showChooseDialog = ref(false)
const activeVersion = ref(0)

const pushCategoryCommonList = ref([])
const showChooseCommonDialog = ref(false)
// 选择弹框内栏目
const treeChoosed = (val) => {
    val.forEach(item => {
      if(!categoryChoose.value.find(ele => ele.id === item.id)){
        categoryChoose.value.push(item)
      }
    })
    categoryChoose.value.forEach(data=>{
        // 获取data的path面包屑
      let _path = data.p_string.split(',')
      _path = _path.map(item => {
        let _category = store.state.category.categoryFlat.find(ele => Number(ele.id) === Number(item))
        if(_category){
          return _category.name
        }else if(!_category && item === ''){
          return data.name
        }else{
          return '主站'
        }
      })
      _path = _path.join('>')
      data.path = _path
    })
}
const handleCommonChoose = (data) => {
  data.checked = !data.checked
  if(data.checked){
    categoryChooseWait.value.push(data) //多选
  }else{
    categoryChooseWait.value = categoryChooseWait.value.filter(item => {
      return item.id !== data.id
    })
  }
}
// 选择栏目
const handleGoChooseCategory = () => {
  // 跳转选择栏目
  pushConfig.pushStep = 1000
  categoryChoose.value = JSON.parse(JSON.stringify(categoryChooseConfirm.value))
}
// 返回投递确认
const handleCancelPush = () => {
  showDialog.value = false
}
// 移除栏目
const handleRemoveCategory = (index) => {
  categoryChoose.value.splice(index,1)
}
const handleChooseCategory = () => {
  showChooseDialog.value = true
  categoryChooseWait.value = JSON.parse(JSON.stringify(categoryChoose.value))
  // 获取可投递栏目树栏目树
  canPushCategoryList({catid: props.pushData.catid}).then((res) => {
    // 过滤 checked
    res.data = res.data.map(item => {
      if(categoryChooseIds.value.includes(item.id)){
        item.checked = true
      }else{
        item.checked = false
      }
      return item
    })
    let list = createTreeData(res.data)
    // 处理是否分版本情况
    list = list.filter(item => {
      return Number(item.type) === 7
    })
    activeVersion.value = 0
    if(list.length > 0){
      pushCategoryList.value = list
    }else{
      pushCategoryList.value = [{id: 0,children: createTreeData(res.data)}]
    }
  })
}
const handleChooseCommonCategory = () => {
  // 获取常用栏目
  showChooseCommonDialog.value = true
  getCommonCategory({catid: props.pushData.catid}).then(res => {
    pushCategoryCommonList.value = res.data.map(item => {
      if(categoryChooseIds.value.includes(item.id)){
        item.checked = true
      }else{
        item.checked = false
      }
      return item
    })
    pushCategoryCommonList.value.forEach(data=>{
      // 获取data的path面包屑
      let _path = data.p_string.split(',')
      _path = _path.map(item => {
        let categoryFlat
        if(store.state.category.categoryFlat){
          categoryFlat = store.state.category.categoryFlat
        }else{
          store.dispatch('category/updateCategory').then(() => {
            categoryFlat = store.state.category.categoryFlat
          })
        }
        let _category = categoryFlat.find(ele => Number(ele.id) === Number(item))
        if(_category){
          return _category.name
        }else if(!_category && item === ''){
          return data.name
        }else{
          return '主站'
        }
      })
      _path = _path.join('>')
      data.path = _path
    })
  })
}
const directEdit = ref(false)
const handleGoMediaEdit = () => {
  dialogWidth.value = '1280px';
  directEdit.value = false
  // 如果栏目选择改变则 重新生成，否则直接跳转编辑
  if(currentArticleCheckList.value.length === currentMedia.value.articleCheckList.length && currentArticleCheckList.value.filter(item => !currentMedia.value.articleCheckList.includes(item))){
    pushConfig.pushStep = 4
  }else{
    currentMedia.value.articleCheckList = JSON.parse(JSON.stringify(currentArticleCheckList.value))
    mediaGenerateLoading.value = true
    mediaContentGenerate({media: currentMedia.value.id,type: currentMedia.value.type,catid: props.pushData.catid,ids: currentMedia.value.articleCheckList,isAllChoose: false}).then(res => {
      currentMedia.value.isGenerating = false
      currentMedia.value.pushData = res.data.success_data
      currentMedia.value.failData = res.data.fail_data
      currentMedia.value.needComplete = res.data.success_data.filter(ele => {return ele.can_publish === 0})
      mediaGenerateLoading.value = false
      pushConfig.pushStep = 4
    })
  }
}

// 保存栏目选择
const handleSaveCategoryChoose = () => {
  pushConfig.pushStep = 2
  categoryChooseConfirm.value = JSON.parse(JSON.stringify(categoryChoose.value))
}
// 直接投递
const handlePushCategory = () => {
  pushLoading.value = true
  let catid_list = categoryChoose.value.map(item => {return item.id})
  let _query = {
    catid: catid_list,
    ids: props.pushData.pushList,
    original_catid: props.pushData.catid,
    isAllChoose: props.pushData.isAllChoose
  }
  pushContent(_query).then(res => {
    pushLoading.value = false
    showDialog.value = false
    if(res.code === 20000){
      ElMessage({
        showClose: true,
        message: '投递成功',
        type: 'success'
      })
    }
  })
}
const handleTreeCheck = () => {
  return false
}
const handleTreeChoosed = () => {
  categoryChoose.value = JSON.parse(JSON.stringify(categoryChooseWait.value))
  categoryChoose.value.forEach(data=>{
    // 获取data的path面包屑
    let _path = data.p_string.split(',')
    _path = _path.map(item => {
      let _category = store.state.category.categoryFlat.find(ele => Number(ele.id) === Number(item))
      if(_category){
        return _category.name
      }else if(!_category && item === ''){
        return data.name
      }else{
        return '主站'
      }
    })
    _path = _path.join('>')
    data.path = _path
  })
  showChooseCommonDialog.value = false
}
const handleCancelChooseCategoryUser = () => {
  categoryChooseWait.value = []
  showChooseCommonDialog.value = false
}
/**************************************************栏目投递******************************************************/


/**************************微信投递流程********************************/
// 外部投递流程
const mediaGenerateLoading = ref(false)
const mediaGenerateAwait = async (media) => {
  // 循环遍历调用接口
  mediaGenerateLoading.value = true
  mediaContentGenerate({media: media.id,type: media.type,catid: props.pushData.catid,ids: props.pushData.pushList,isAllChoose: props.pushData.isAllChoose}).then(res => {
    media.isGenerating = false
    media.pushData = res.data.success_data
    media.failData = res.data.fail_data
    media.needComplete = res.data.success_data.filter(item => {return item.can_publish === 0})
    media.articleCheckList = []
    mediaGenerateLoading.value = false
    handleViewDetail(media)
  })
}
// 等待跳转
const mediaGenerate = (medias) => {
  medias.forEach(item => {
      mediaContentGenerate({media: item.id,type: item.type,catid: props.pushData.catid,ids: props.pushData.pushList,isAllChoose: props.pushData.isAllChoose}).then(res => {
        item.isGenerating = false
        item.pushData = res.data.success_data
        item.failData = res.data.fail_data
        item.needComplete = res.data.success_data.filter(ele => {return ele.can_publish === 0})
        item.articleCheckList = []
    })
  })
}
// 外部投递 查看列表详情
const currentMedia = ref({})
const currentArticleList = ref([])      //浅拷贝赋值
const currentArticleCheckList = ref([])
const handleViewDetail = (data) => {
  pushConfig.pushStep = 3
  currentMedia.value = data
  // 查询列表
  /**********
      @name:
      @describtion: params: {
        catid: id,
        ids: Array, 文章选择数组
        isAllChoose Boolean,是否全选
      }
      @author:liubingye
      @date:2023-06-19 10:14:00
  ***********/
  getArticleList({catid: props.pushData.catid,ids: props.pushData.pushList,isAllChoose: props.pushData.isAllChoose}).then(res => {
    currentArticleList.value = res.data
    //如果 articleCheckList 为空则默认勾选前几个,如果不为空则勾选articleCheckList
    if(data.articleCheckList.length === 0){
      let num = data.pushData.length
      let i = 0
      currentArticleList.value = currentArticleList.value.map(item => {
        if(item.can_push === 1 && i < num){
          item.checked = true
          data.articleCheckList.push(item.id)
          i++
        }else{
          item.checked = false
        }
        return item
      })
    }else{
      currentArticleList.value = currentArticleList.value.map(item => {
        if(data.articleCheckList.includes(item.id)){
          item.checked = true
        }else{
          item.checked = false
        }
        return item
      })
    }
    currentArticleCheckList.value = JSON.parse(JSON.stringify(data.articleCheckList))
  })
}
const handleEditWithoutMedia = (data) => {
  dialogWidth.value="1280px"
  // 编辑
  currentMedia.value = data
  directEdit.value = true
  pushConfig.pushStep = 4
}
const handleCheckedArticleList = (data) => {
  if(data.checked && currentArticleCheckList.value.length >= currentMedia.value.publish_limit){
    data.checked = !data.checked
    ElMessage({
      showClose: true,
      message: currentMedia.value.name + '最多只能选择' + currentMedia.value.publish_limit + '项',
      type: 'warning'
    })
  }else if(data.checked){
    currentArticleCheckList.value.push(data.id)
  }else if(!data.checked){
    let _index = currentArticleCheckList.value.indexOf(data.id)
    currentArticleCheckList.value.splice(_index,1)
  }
}
const handleCancelWithoutMediaPush = () => {
  pushConfig.pushStep = 2
  confirmWithoutType.value.find(item => item.id === currentMedia.value.id).checked = false
}
const handleBackArticleList = () => {
  pushConfig.pushStep = 3
  resetDialogWidth()
}

const publishDataRef = ref()
const handlePushWithout = () => {
  publishDataRef.value.getArticles().then(res => {
    if(res){
      // 调用投递接口
      let articles = res
      pushMediaArticle({media: currentMedia.value.id,article: articles}).then(() => {
        ElMessage({
          showClose: true,
          message: '投递成功',
          type: 'success'
        })
        // 关闭弹框
        showDialog.value = false
      })
    }
  })
}
const handleSaveWithoutEdit = () => {
  publishDataRef.value.getArticles().then(res => {
    if(res){
      // 保存文章内容
      let articles = res
      articles.map(item => {
        item.can_publish = 1
        return item
      })
      currentMedia.value.pushData = articles
      currentMedia.value.needComplete = []
      pushConfig.pushStep = 2
    }
  })
}
/****************************微信投递*********************************/
const handleBatchPush = () => {
  // promise.all 请求
  let promise_list = []
  // 内部媒体投递验证
  // 1.网站栏目  验证栏目选择是否为空
  let insideType = confirmInsideType.value.find(ele => ele.id === 1)
  if(insideType && insideType.checked && categoryChooseConfirm.value.length === 0){
    ElMessage({
      showClose: true,
      message: '请选择投递栏目',
      type: 'warning'
    })
    return false
  }else if(insideType && insideType.checked){
    // 请求栏目投递接口
    let _query = {
      catid: categoryChooseConfirm.value.map(item => {return item.id}),
      ids: props.pushData.pushList,
      original_catid: props.pushData.catid,
      isAllChoose: props.pushData.isAllChoose
    }
    let category_push = new Promise((resolve,reject) => {
      pushContent(_query).then(res => {resolve(res)}).catch(() => {reject()})
    })
    promise_list.push(category_push)
  }
  try {
    confirmWithoutType.value.forEach(item => {
      if(item.checked && item.needComplete.length > 0){
        ElMessage({
          showClose: true,
          message: item.name + '内容待完善',
          type: 'warning'
        })
        throw Error()
      }else if(item.checked){
        // 外部媒体投递接口
        let media_push = new Promise((resolve,reject) => {
          pushMediaArticle({media: item.id,article: item.pushData}).then(res => {resolve(res)}).catch(() => {reject()})
        })
        promise_list.push(media_push)
      }
    })
  }catch(e) {
    return false
  }
  pushLoading.value = true
  Promise.all(promise_list).then(() => {
    ElMessage({
      showClose: true,
      message: '投递并发布成功',
      type: 'success'
    })
    pushLoading.value = false
    // 关闭弹框结束
    showDialog.value = false
  })
}
</script>

<style scoped lang="scss">
.ruifox-media-push-step{
  ::v-deep(.el-dialog.media-push-dialog){
    &>.el-dialog__body{
      padding: 0 50px!important;
    }
  }
}
.ruifox-media-push{
  ::v-deep(.el-dialog.media-push-dialog){
    &>.el-dialog__header{
      border-bottom: none;
    }
    &>.el-dialog__body{
      padding: 0 20px;
    }
    &>.el-dialog__footer{
      border-top: none;
    }
  }
  .dialog-footer-flex{
    display: flex;
    justify-content: space-between;
  }
  .push-step{
    .push-type-box{
      h2{
        font-size: 16px;
        line-height: 32px;
        font-weight: normal;
        color: #333333;
      }
      .inner-push-type-box{
        display: flex;
        flex-wrap: wrap;
        min-height: 90px;
        .push-type-item{
          overflow: hidden;
          margin-right: 20px;
          height: 90px;
          width: 200px;
          border: 1px solid #fff;
          border-radius: 4px;
          box-shadow: 0 0 10px rgba(0,0,0,0.1);
          box-sizing: border-box;
          padding: 25px 20px;
          cursor: pointer;
          display: flex;
          flex-direction: column;
          justify-content: center;
          margin-bottom: 20px;
          position: relative;
          transition: all 0.2s;
          &.checked{
            border-color: $mainColor;
            .check-box{
              .check-box-bg{
                background-color: $mainColor;
              }
              opacity: 1;
            }
          }
          &:not(.is-disabled):hover{
            border-color: $mainColor;
            .check-box{
              opacity: 1;
            }
          }
          &.checked:hover{
            .check-box{
              .check-box-bg{
                background-color: $hoverColor;
              }
            }
          }
          .check-box{
            position: absolute;
            left: 0;top: 0;
            width: 40px;height: 40px;
            overflow: hidden;
            opacity: 0;
            transition: all 0.2s;
            .check-box-bg{
              position: absolute;
              height: 100%;width: 100%;
              transform: rotate(45deg);
              background-color: #C9C9C9;
              top: -20px;left: -20px;
              i{
                position: absolute;
                display: block;
                font-size: 16px;
                right: 0;
                top: 12px;
                transform: rotate(-45deg);
                color: #FFFFFF;
              }
            }
          }
          p.type-title{
            font-size: 18px;
            display: flex;
            align-items: center;
            margin-bottom: 5px;
            i{
              color: $mainColor;
              margin-right: 5px;
            }
          }
          span.type-desc{
            font-size: 12px;
            color: #aaa;
          }
        }
        .push-type-item.is-disabled{
          cursor: not-allowed;
          p.type-title{
            color: #C9C9C9!important;
            i{
              color: #C9C9C9!important;
            }
          }
          span.type-desc{
            color: #C9C9C9!important;
          }
        }
        .push-type-item:nth-child(4n){
          margin-right: 0;
        }
      }
    }
  }
  .push-type-confirm{
    h2{
      font-size: 16px;
      color: #333333;
      font-weight: normal;
      line-height: 32px;
      span{
        color: $mainColor;
      }
    }
    .confirm-type-box{
      .confirm-type-item{
        min-height: 90px;
        box-shadow: 0 0 10px rgba(0,0,0,0.1);
        padding: 15px 40px;
        border-radius: 4px;
        margin-bottom: 10px;
        box-sizing: border-box;
        width: 100%;
        .inner-confirm-type{
          display: flex;
          align-items: center;
          min-height: 60px;
          h3{
            font-size: 18px;
            font-weight: normal;
            color: #333;
            width: 210px;
            i{
              color: $mainColor;
            }
          }
          .push-message{
            flex: 1;
            .no-category{
              p{
                color: #FF5240;
                i{
                  margin-right: 5px;
                }
              }
            }
            .has-category{
              display: flex;
              i{margin-right: 5px;color: #2CBF77;}
              align-items: center;
              .category-list{
                li{
                  height: 20px;
                  box-sizing: border-box;
                  border: 1px solid #E4E4E4;
                  background-color: $checkColor;
                  border-radius: 4px;
                  font-size: 12px;
                  line-height: 20px;
                  margin-bottom: 4px;
                  padding: 0 4px;
                  color: #333333;
                  width: max-content;
                }
              }
            }
            .is-loading{
              color: #aaaaaa;
              font-size: 14px;
              i{
                font-size: 16px;
              }
            }
            .loaded{
              display: flex;
              align-items: center;
              i{margin-right: 5px;}
              i.success{
                color: #2CBF77;
              }
              i.warning{
                color: #FF9700;
              }
              i.error{
                color: #FF5240;
              }
              p{
                span{
                  color: #333333;
                  font-size: 14px;
                }
                span.error{
                  strong{
                    color: #FF5240;
                  }
                }
                span+span:before{
                  content: '，';
                }
              }
            }
          }
        }
        &.without-type{
          .push-option{
            display: flex;
            a{
              margin-left: 15px;
            }
          }
        }
      }
    }
  }
  .push-category-choose{
    .push-category-btn{
      margin: 20px 0;
    }
    .category-choose-box{
      height: 430px;
      border: 1px solid #E4E4E4;
      .no-data{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 430px;
        i{
          font-size: 90px;
          color: #C9C7CF;
        }
        p{
          font-size: 14px;
          margin-bottom: 10px;
          color: #C9C7CF;
        }
      }
      .category-choose-list{
        .category-choose-item{
          display: flex;
          justify-content: space-between;
          align-items: center;
          height: 48px;
          border-bottom: 1px solid #E4E4E4;
          padding: 0 20px;
          .choose-item-left{
            display: flex;
            align-items: center;
            span.choose-item-id{
              font-size: 14px;
              color: #aaaaaa;
              margin-right: 15px;
            }
            p.choose-item-title{
              color: #333333;
              @include textEllipsis(16px,1)
            }
          }
        }
      }
      .category-tree-box{
        width: 100%;
        box-sizing: border-box;
        border: 1px solid #E4E4E4;
        height: 600px;
        display: flex;
        overflow: hidden;
        .version-choose-box{
          width: 160px;
          border-right: 1px solid #E4E4E4;
          padding: 10px 0;
          li.version-item{
            height: 40px;
            line-height: 40px;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            cursor: pointer;
            i{
              font-size: 12px;
              color: #AAAAAA;
            }
            span{
              font-size: 14px;
              color: #333;
            }
          }
          li.version-item.active{
            span{
              font-weight: bold;
              color: $mainColor;
            }
          }
        }
        .category-tree-list{
          flex: 1;
          .category-tree-children{
            width: 100%;
            .tree-content{
              ::v-deep(.el-tree-node__label){
                width: 100%;
              }
              ::v-deep(.el-tree-node__content){
                height: 40px;
              }
              .tree-node-category{
                height: 40px;
                width: 100%;
                box-sizing: border-box;
                display: flex;
                align-items: center;
                padding: 0 20px 0 0;
                justify-content: space-between;
              }
            }
          }
        }
        .common-list{
          width: 100%;
          .common-item{
            height: 48px;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #E4E4E4;
            padding: 0 20px;
            cursor: pointer;
          }
        }
      }
    }
  }
  .push-without-detail{
    .detail-title{
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      h3{
        font-weight: normal;
        color: #333333;
      }
      div{
        color: #AAAAAA;
        display: flex;
        align-items: center;
        p{
          color: #333333;
        }
        span{
          color: #FF5240;
        }
      }
    }
    .inner-detail{
      height: 465px;
      border: 1px solid #E4E4E4;
      li{
        border-bottom: 1px solid #E4E4E4;
        box-sizing: border-box;
        padding: 0 20px;
        width: 100%;
        display: flex;
        height: 48px;
        align-items: center;
        justify-content: space-between;
        .inner-detail-left{
          flex: 1;
          display: flex;
          align-items: center;
          p{
            flex: 1;
            @include textEllipsis(16px,1);
            &.is-disabled{
              color: #aaaaaa;
            }
          }
          span.model-tip{
            display: block;
            box-sizing: border-box;
            height: 20px;
            line-height: 20px;
            padding: 0 5px;
            border: 1px solid $mainColor;
            border-radius: 2px;
            font-size: 12px;
            color: $mainColor;
            margin-right: 10px;
          }
        }
      }
    }
  }
  .push-option-btn{
    display: block;
    height: 26px;
    box-sizing: border-box;
    padding: 0 10px;
    line-height: 24px;
    border: 1px solid $mainColor;
    color: $mainColor;
    font-size: 16px;
    border-radius: 4px;
    transition: all 0.2s;
    &:hover{
      color: #fff;
      background-color: $mainColor;
    }
  }
}
</style>
